/**
 * 产品管理模块 Mock 数据
 * @description 线路产品管理相关的模拟数据和API接口Mock
 * @author CRM开发团队
 * @version 1.0.0
 */

import Mock from 'mockjs'
import { faker } from '@faker-js/faker'
import type { Product, ProductStatistics, ProductListQuery } from '@/api/product'
import { createResponse, createPageResponse } from './index'
import logger from '@/utils/logger'

// 产品分类数据
const productCategories = [
  {
    value: '国内游',
    label: '国内游',
    children: [
      { value: '华北线', label: '华北线' },
      { value: '华东线', label: '华东线' },
      { value: '华南线', label: '华南线' },
      { value: '华中线', label: '华中线' },
      { value: '西南线', label: '西南线' },
      { value: '西北线', label: '西北线' },
      { value: '东北线', label: '东北线' }
    ]
  },
  {
    value: '出境游',
    label: '出境游',
    children: [
      { value: '东南亚', label: '东南亚' },
      { value: '日韩', label: '日韩' },
      { value: '欧洲', label: '欧洲' },
      { value: '美洲', label: '美洲' },
      { value: '澳新', label: '澳新' },
      { value: '其他', label: '其他' }
    ]
  },
  {
    value: '周边游',
    label: '周边游',
    children: [
      { value: '一日游', label: '一日游' },
      { value: '二日游', label: '二日游' },
      { value: '三日游', label: '三日游' }
    ]
  },
  {
    value: '定制游',
    label: '定制游',
    children: [
      { value: '家庭定制', label: '家庭定制' },
      { value: '团队定制', label: '团队定制' },
      { value: '主题定制', label: '主题定制' }
    ]
  }
]

// 产品标签
const productTags = [
  '纯玩无购物', '豪华酒店', '美食专线', '摄影采风', '温泉养生',
  '登山徒步', '文化深度', '自然风光', '中老年专线', '亲子游',
  '情侣游', '单身游', '健康人群', '需要照顾', '行动不便适宜',
  '经济实惠', '舒适标准', '豪华品质', '至尊享受'
]

// 生成随机产品数据
const generateProduct = (id?: string): Product => {
  const categories = [
    { primary: '国内游', secondary: '华东线' },
    { primary: '国内游', secondary: '华南线' },
    { primary: '出境游', secondary: '东南亚' },
    { primary: '出境游', secondary: '日韩' },
    { primary: '周边游', secondary: '二日游' },
    { primary: '定制游', secondary: '家庭定制' }
  ]
  
  const statuses = ['正常销售', '暂停销售', '即将上线', '已下架', '季节性暂停']
  const inventoryStatuses = ['充足', '紧张', '不足', '售罄']
  
  const category = faker.helpers.arrayElement(categories)
  const status = faker.helpers.arrayElement(statuses)
  const inventoryStatus = faker.helpers.arrayElement(inventoryStatuses)
  
  const basePrice = faker.datatype.number({ min: 1000, max: 8000 })
  const totalStock = faker.datatype.number({ min: 20, max: 100 })
  const soldCount = faker.datatype.number({ min: 0, max: totalStock - 5 })
  const availableStock = totalStock - soldCount
  
  return {
    id: id || faker.datatype.uuid(),
    productCode: `PRD${new Date().getFullYear()}${faker.datatype.number({ min: 1000, max: 9999 })}`,
    name: faker.helpers.arrayElement([
      '桂林山水精品3日游',
      '九寨沟黄龙双飞5日游',
      '厦门鼓浪屿温馨4日游',
      '西藏拉萨布达拉宫7日游',
      '云南大理丽江双古城6日游',
      '张家界森林公园4日游',
      '海南三亚天涯海角5日游',
      '北京故宫长城经典4日游',
      '泰国曼谷芭提雅6日游',
      '日本东京大阪7日游',
      '新马泰经典10日游',
      '欧洲四国深度12日游'
    ]),
    subtitle: faker.lorem.sentence(6),
    category,
    destination: [
      faker.helpers.arrayElement(['桂林', '九寨沟', '厦门', '拉萨', '大理', '张家界', '三亚', '北京', '曼谷', '东京', '新加坡', '巴黎'])
    ],
    duration: faker.datatype.number({ min: 3, max: 12 }),
    description: faker.lorem.paragraph(3),
    highlights: Array.from({ length: faker.datatype.number({ min: 3, max: 6 }) }, () => faker.lorem.sentence()),
    
    // 价格信息
    pricing: {
      adult: basePrice,
      child: Math.floor(basePrice * 0.7),
      infant: Math.floor(basePrice * 0.3),
      senior: Math.floor(basePrice * 0.8),
      member: Math.floor(basePrice * 0.9)
    },
    
    // 库存信息
    inventory: {
      totalStock,
      availableStock,
      soldCount,
      reservedStock: faker.datatype.number({ min: 2, max: 10 }),
      minGroup: faker.datatype.number({ min: 6, max: 20 })
    },
    
    // 状态信息
    status,
    inventoryStatus,
    
    // 销售数据
    salesData: {
      monthSales: faker.datatype.number({ min: 0, max: 50 }),
      totalSales: faker.datatype.number({ min: 50, max: 500 }),
      avgRating: faker.datatype.float({ min: 3.5, max: 5.0, precision: 0.1 })
    },
    
    // 时间信息
    createdAt: faker.date.past(2).toISOString(),
    updatedAt: faker.date.recent(30).toISOString(),
    createdBy: faker.name.fullName(),
    updatedBy: faker.name.fullName(),
    
    // 产品图片
    mainImage: `https://picsum.photos/400/300?random=${faker.datatype.number({ min: 1, max: 1000 })}`,
    images: Array.from({ length: faker.datatype.number({ min: 3, max: 8 }) }, (_, index) => 
      `https://picsum.photos/400/300?random=${faker.datatype.number({ min: 1000, max: 2000 }) + index}`
    ),
    
    // 产品标签
    tags: faker.helpers.arrayElements(productTags, faker.datatype.number({ min: 2, max: 5 })),
    
    // 价格变化（用于趋势显示）
    priceChange: faker.datatype.number({ min: -15, max: 20 })
  }
}

// 生成产品列表数据
const generateProductList = (total: number = 100): Product[] => {
  return Array.from({ length: total }, () => generateProduct())
}

// Mock产品列表数据（模拟数据库数据）
let mockProductList = generateProductList(100)

// 统计数据
const calculateStatistics = (): ProductStatistics => ({
  totalProducts: mockProductList.length,
  onSaleProducts: mockProductList.filter(p => p.status === '正常销售').length,
  inventoryWarnings: mockProductList.filter(p => p.inventoryStatus === '不足' || p.inventoryStatus === '紧张').length,
  monthSales: mockProductList.reduce((sum, p) => sum + p.salesData.monthSales, 0),
  avgPrice: Math.floor(mockProductList.reduce((sum, p) => sum + p.pricing.adult, 0) / mockProductList.length),
  priceGrowth: faker.datatype.number({ min: -10, max: 15 }),
  salesGrowth: faker.datatype.number({ min: -5, max: 25 })
})

/**
 * 产品列表筛选函数
 */
const filterProducts = (query: any) => {
  const {
    keyword = '',
    status = '',
    category = '',
    inventoryStatus = '',
    priceMin,
    priceMax,
    tags = [],
    sortBy = '',
    sortOrder = 'desc'
  } = query

  let filteredProducts = [...mockProductList]

  // 关键词搜索
  if (keyword) {
    filteredProducts = filteredProducts.filter(product =>
      product.name.includes(keyword) ||
      product.productCode.includes(keyword) ||
      product.destination.some(d => d.includes(keyword))
    )
  }

  // 状态筛选
  if (status) {
    filteredProducts = filteredProducts.filter(product => product.status === status)
  }

  // 分类筛选
  if (category) {
    filteredProducts = filteredProducts.filter(product => 
      product.category.primary.includes(category) || 
      product.category.secondary.includes(category)
    )
  }

  // 库存状态筛选
  if (inventoryStatus) {
    filteredProducts = filteredProducts.filter(product => product.inventoryStatus === inventoryStatus)
  }

  // 价格范围筛选
  if (priceMin !== undefined && priceMin !== null) {
    filteredProducts = filteredProducts.filter(product => product.pricing.adult >= Number(priceMin))
  }
  if (priceMax !== undefined && priceMax !== null) {
    filteredProducts = filteredProducts.filter(product => product.pricing.adult <= Number(priceMax))
  }

  // 标签筛选
  if (Array.isArray(tags) && tags.length > 0) {
    filteredProducts = filteredProducts.filter(product =>
      tags.some(tag => product.tags.includes(tag))
    )
  }

  // 排序
  if (sortBy) {
    filteredProducts.sort((a, b) => {
      let aValue: any = a
      let bValue: any = b

      if (sortBy.includes('.')) {
        const keys = sortBy.split('.')
        aValue = keys.reduce((obj, key) => obj[key], a)
        bValue = keys.reduce((obj, key) => obj[key], b)
      } else {
        aValue = a[sortBy as keyof Product]
        bValue = b[sortBy as keyof Product]
      }

      if (typeof aValue === 'string') {
        return sortOrder === 'asc' 
          ? aValue.localeCompare(bValue) 
          : bValue.localeCompare(aValue)
      }

      return sortOrder === 'asc' ? aValue - bValue : bValue - aValue
    })
  }

  return filteredProducts
}

/**
 * 设置产品管理Mock接口
 */
export const setupProductMock = (): void => {
  logger.info('[MOCK] 设置产品管理Mock接口...')
  console.log('[MOCK] 开始设置产品管理Mock接口')

  // 先测试一个简单的路由 - 使用正确的格式
  Mock.mock('/api/products/test', 'get', () => {
    console.log('[MOCK] 测试路由被调用')
    return createResponse('test ok', '测试成功')
  })

  // 注册所有具体路径的接口，使用精确匹配
  const routes = [
    // 获取产品列表
    {
      url: '/api/products/list',
      method: 'get',
      handler: (options: any) => {
        console.log('[MOCK] ===== 获取产品列表被调用 =====')
        console.log('[MOCK] Options:', options)
        const url = new URL('http://localhost' + options.url)
        const query: any = {}
        
        // 解析查询参数
        url.searchParams.forEach((value, key) => {
          if (key === 'tags' && value) {
            query[key] = value.split(',').filter(Boolean)
          } else if (key === 'priceMin' || key === 'priceMax') {
            const numValue = Number(value)
            if (!isNaN(numValue)) {
              query[key] = numValue
            }
          } else {
            query[key] = value
          }
        })

        const page = Number(query.page) || 1
        const pageSize = Number(query.pageSize) || 20

        const filteredProducts = filterProducts(query)
        
        // 分页
        const total = filteredProducts.length
        const startIndex = (page - 1) * pageSize
        const endIndex = startIndex + pageSize
        const items = filteredProducts.slice(startIndex, endIndex)

        return createResponse({
          items,
          total,
          page,
          pageSize
        }, '获取产品列表成功')
      }
    },
    
    // 获取产品统计数据
    {
      url: '/api/products/statistics',
      method: 'get',
      handler: () => {
        console.log('[MOCK] 获取产品统计数据被调用')
        return createResponse(calculateStatistics(), '获取统计数据成功')
      }
    },
    
    // 获取产品分类
    {
      url: '/api/products/categories',
      method: 'get',
      handler: () => {
        console.log('[MOCK] 获取产品分类被调用')
        return createResponse(productCategories, '获取产品分类成功')
      }
    },
    
    // 获取产品标签
    {
      url: '/api/products/tags',
      method: 'get',
      handler: () => {
        console.log('[MOCK] 获取产品标签被调用')
        return createResponse(productTags, '获取产品标签成功')
      }
    },
    
    // 搜索建议
    {
      url: '/api/products/search-suggestions',
      method: 'get',
      handler: (options: any) => {
        console.log('[MOCK] 获取搜索建议被调用')
        const url = new URL('http://localhost' + options.url)
        const keyword = url.searchParams.get('keyword') || ''
        
        if (!keyword || keyword.length < 2) {
          return createResponse([], '搜索建议获取成功')
        }

        const suggestions = new Set<string>()
        
        mockProductList.forEach(product => {
          if (product.name.includes(keyword)) {
            suggestions.add(product.name)
          }
          if (product.productCode.includes(keyword)) {
            suggestions.add(product.productCode)
          }
          product.destination.forEach(dest => {
            if (dest.includes(keyword)) {
              suggestions.add(dest)
            }
          })
        })

        return createResponse(Array.from(suggestions).slice(0, 10), '搜索建议获取成功')
      }
    },
    
    // 批量操作产品
    {
      url: '/api/products/batch-operation',
      method: 'post',
      handler: (options: any) => {
        console.log('[MOCK] 批量操作产品被调用')
        const { ids, operation, data } = JSON.parse(options.body)

        let processedCount = 0
        
        switch (operation) {
          case 'delete':
            ids.forEach((id: string) => {
              const index = mockProductList.findIndex(p => p.id === id)
              if (index !== -1) {
                mockProductList.splice(index, 1)
                processedCount++
              }
            })
            break

          case 'updateStatus':
            ids.forEach((id: string) => {
              const product = mockProductList.find(p => p.id === id)
              if (product && data?.status) {
                product.status = data.status
                product.updatedAt = new Date().toISOString()
                processedCount++
              }
            })
            break

          case 'updatePrice':
            ids.forEach((id: string) => {
              const product = mockProductList.find(p => p.id === id)
              if (product && data?.priceAdjustment) {
                const adjustment = data.priceAdjustment
                if (adjustment.type === 'percentage') {
                  product.pricing.adult = Math.floor(product.pricing.adult * (1 + adjustment.value / 100))
                } else if (adjustment.type === 'fixed') {
                  product.pricing.adult += adjustment.value
                }
                product.updatedAt = new Date().toISOString()
                processedCount++
              }
            })
            break

          default:
            return createResponse(null, '不支持的操作类型', 400)
        }

        return createResponse({ processedCount }, '批量操作成功')
      }
    },
    
    // 创建产品
    {
      url: '/api/products',
      method: 'post',
      handler: (options: any) => {
        console.log('[MOCK] 创建产品被调用')
        const body = JSON.parse(options.body)
        const newProduct = generateProduct()
        Object.assign(newProduct, body, {
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        })
        mockProductList.unshift(newProduct)

        return createResponse(newProduct, '产品创建成功')
      }
    }
  ]

  // 注册所有路由
  routes.forEach(route => {
    console.log(`[MOCK] 注册路由: ${route.method.toUpperCase()} ${route.url}`)
    Mock.mock(route.url, route.method, (options: any) => {
      console.log(`[MOCK] 路由被调用: ${route.method.toUpperCase()} ${route.url}`)
      console.log('[MOCK] 请求选项:', options)
      try {
        const result = route.handler(options)
        console.log('[MOCK] 响应结果:', result)
        return result
      } catch (error) {
        console.error(`[MOCK] 路由处理错误:`, error)
        return createResponse(null, '服务器内部错误', 500)
      }
    })
  })

  // 注册正则表达式路由（放在最后，避免冲突）
  const regexRoutes = [
    // 获取产品详情
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)$/,
      method: 'get',
      handler: (options: any) => {
        const url = options.url
        console.log('[MOCK] 获取产品详情被调用, URL:', url)
        
        const id = url.split('/').pop()?.split('?')[0]
        const product = mockProductList.find(p => p.id === id)
        
        if (!product) {
          console.log('[MOCK] 产品不存在, ID:', id)
          return createResponse(null, '产品不存在', 404)
        }

        return createResponse(product, '获取产品详情成功')
      }
    },
    
    // 更新产品
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)$/,
      method: 'put',
      handler: (options: any) => {
        const id = options.url.split('/').pop()
        const body = JSON.parse(options.body)
        const index = mockProductList.findIndex(p => p.id === id)
        
        if (index === -1) {
          return createResponse(null, '产品不存在', 404)
        }

        Object.assign(mockProductList[index], body, {
          updatedAt: new Date().toISOString()
        })

        return createResponse(mockProductList[index], '产品更新成功')
      }
    },
    
    // 删除产品
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)$/,
      method: 'delete',
      handler: (options: any) => {
        const id = options.url.split('/').pop()
        const index = mockProductList.findIndex(p => p.id === id)
        
        if (index === -1) {
          return createResponse(null, '产品不存在', 404)
        }

        mockProductList.splice(index, 1)
        return createResponse(true, '产品删除成功')
      }
    },
    
    // 复制产品
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)\/copy$/,
      method: 'post',
      handler: (options: any) => {
        const id = options.url.split('/')[3]
        const { name } = JSON.parse(options.body)
        const originalProduct = mockProductList.find(p => p.id === id)
        
        if (!originalProduct) {
          return createResponse(null, '原产品不存在', 404)
        }

        const newProduct = {
          ...originalProduct,
          id: faker.datatype.uuid(),
          productCode: `PRD${new Date().getFullYear()}${faker.datatype.number({ min: 1000, max: 9999 })}`,
          name,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        }

        mockProductList.unshift(newProduct)
        return createResponse(newProduct, '产品复制成功')
      }
    },
    
    // 更新产品状态
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)\/status$/,
      method: 'patch',
      handler: (options: any) => {
        const id = options.url.split('/')[3]
        const { status } = JSON.parse(options.body)
        const product = mockProductList.find(p => p.id === id)
        
        if (!product) {
          return createResponse(null, '产品不存在', 404)
        }

        product.status = status
        product.updatedAt = new Date().toISOString()

        return createResponse(product, '状态更新成功')
      }
    },
    
    // 获取价格历史
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)\/price-history$/,
      method: 'get',
      handler: () => {
        const priceHistory = Array.from({ length: 12 }, (_, index) => ({
          date: new Date(Date.now() - (11 - index) * 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          price: faker.datatype.number({ min: 2000, max: 5000 }),
          change: faker.datatype.number({ min: -200, max: 300 })
        }))

        return createResponse(priceHistory, '获取价格历史成功')
      }
    },
    
    // 获取销售分析数据
    {
      pattern: /^\/api\/products\/([a-zA-Z0-9\-]+)\/sales-analytics$/,
      method: 'get',
      handler: () => {
        const analyticsData = {
          salesTrend: Array.from({ length: 12 }, (_, index) => ({
            month: `${new Date().getFullYear()}-${String(index + 1).padStart(2, '0')}`,
            sales: faker.datatype.number({ min: 10, max: 100 }),
            revenue: faker.datatype.number({ min: 50000, max: 300000 })
          })),
          customerSegment: [
            { segment: '新客户', count: faker.datatype.number({ min: 20, max: 50 }), percentage: 45 },
            { segment: '老客户', count: faker.datatype.number({ min: 30, max: 60 }), percentage: 55 }
          ],
          popularDestinations: [
            { destination: '桂林', bookings: faker.datatype.number({ min: 50, max: 100 }) },
            { destination: '九寨沟', bookings: faker.datatype.number({ min: 40, max: 90 }) },
            { destination: '厦门', bookings: faker.datatype.number({ min: 30, max: 80 }) }
          ]
        }

        return createResponse(analyticsData, '获取销售分析数据成功')
      }
    }
  ]

  // 注册正则表达式路由
  regexRoutes.forEach(route => {
    console.log(`[MOCK] 注册正则路由: ${route.method.toUpperCase()} ${route.pattern}`)
    Mock.mock(route.pattern, route.method, (options: any) => {
      console.log(`[MOCK] 正则路由被调用: ${route.method.toUpperCase()} ${route.pattern}`)
      console.log('[MOCK] 请求选项:', options)
      try {
        const result = route.handler(options)
        console.log('[MOCK] 响应结果:', result)
        return result
      } catch (error) {
        console.error(`[MOCK] 正则路由处理错误:`, error)
        return createResponse(null, '服务器内部错误', 500)
      }
    })
  })

  console.log('[MOCK] 产品管理Mock接口设置完成')
  logger.info('[MOCK] 产品管理Mock接口设置完成')
}

// 导出生成函数供其他模块使用
export {
  generateProduct,
  generateProductList,
  productCategories,
  productTags
}